<!-- 财务管理 -->
<template>
  <div class="navigation">
    <div class="navigation-content">
      <div class="flex-center">
        <div class="left-menu">
          <div
            class="menu-group"
            v-for="(item, index) in routeList[titleList[0]]"
            :key="index"
            v-if="item.children.length > 0"
          >
            <div
              class="menu-group-item1"
              v-for="(item1, index1) in item.children"
              :key="index1"
              @click="routeClick(item1)"
              :class="{ placeholder: item1.isPlaceholder }"
            >
              <img :src="titleToImage[item1.title]" :alt="item1.title" v-if="titleToImage[item1.title]" />
              {{ item1.title }}
            </div>
          </div>
        </div>
      </div>

      <div class="query_statistics">
        <div class="query_statistics_title">相关查询统计</div>
        <div class="query_statistics_content">
          <div v-for="(r, i) in titleList" :key="i">
            <div
              v-if="i != 0"
              class="query_statistics_content_item"
              v-for="(item, index) in routeList[r]"
              :key="index"
              @click="routeClick(item)"
            >
              <div class="yuan"></div>
              {{ item.title }}
            </div>
            <a-divider v-if="i != 0 && i !== titleList.length - 1" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import subMenu from '../../menu/Sidebar/submenu'
import { getAction } from '@/api/manage'
import Vue from 'vue'
import { handlePermissions, handlePagePermissions, handleOtherPerms } from '@/utils'
export default {
  components: {},
  name: 'paymentMenu',
  props: {},
  watch: {
    '$store.getters.openAccountValue'(val) {
      this.openAccount = val
      if (val === 3) {
        this.isOpenAccount = true
      } else {
        this.isOpenAccount = false
      }
    },
  },
  data() {
    return {
      path: '/payment',
      routeList: [],
      titleList: [],
      dialogVisible: false,
      isOpenAccount: false, // 开账状态
      openAccount: 0, // 开账状态
      printPermissions: false, //打印模板设置权限
      // 定义菜单分组映射
      menuGroups: {
        '收付款单': [
          '收款结算单',
          '付款结算单',
          '其他收入单',
          '应收款管理',
          '应付款管理',
          '一般费用单',
          '转账单',
          '成本调整单'
        ],
        '物流单据': [
          '物流代收',
          '物流代付',
          '物流运费'
        ],
        '调整单据': [
          '资金增加',
          '资金减少',
          '应收款增加',
          '应收款减少',
          '应付款增加',
          '应付款减少'
        ],
        '发票单据': [
          '进项发票管理',
          '销项发票管理'
        ]
      }
    }
  },
  computed: {
    cashPermissions() {
      return handlePermissions('现金银行统计表')
    },
    titleToImage() {
      return {
        '收款结算单': require('@/assets/home/financeMenu/skjsd-menu.png'),
        '付款结算单': require('@/assets/home/financeMenu/fkjsd-menu.png'),
        '其他收入单': require('@/assets/home/financeMenu/qtsrd-menu.png'),
        '应收款管理': require('@/assets/home/financeMenu/yskgl-menu.png'),
        '应付款管理': require('@/assets/home/financeMenu/yfkgl-menu.png'),
        '一般费用单': require('@/assets/home/financeMenu/ybfyd-menu.png'),
        '转账单': require('@/assets/home/financeMenu/zzd-menu.png'),
        '成本调整单': require('@/assets/home/financeMenu/cbtzd-menu.png'),
        '物流代收': require('@/assets/home/financeMenu/wlds-menu.png'),
        '物流代付': require('@/assets/home/financeMenu/wldf-menu.png'),
        '物流运费': require('@/assets/home/financeMenu/wlyf-menu.png'),
        '资金增加': require('@/assets/home/financeMenu/zjzj-menu.png'),
        '资金减少': require('@/assets/home/financeMenu/zjjs-menu.png'),
        '应收款增加': require('@/assets/home/financeMenu/yskzj-menu.png'),
        '应收款减少': require('@/assets/home/financeMenu/yskjs-menu.png'),
        '应付款增加': require('@/assets/home/financeMenu/yfkzj-menu.png'),
        '应付款减少': require('@/assets/home/financeMenu/yfkjs-menu.png'),
        '进项发票管理': require('@/assets/home/financeMenu/jxfpgl-menu.png'),
        '销项发票管理': require('@/assets/home/financeMenu/xxfpgl-menu.png'),
      }
    },
  },
  mounted() {
    this.printPermissions = handleOtherPerms('打印模板设置')
    this.openAccount = this.$store.getters.openAccountValue
    if (this.openAccount === 3) {
      this.isOpenAccount = true
    } else {
      this.isOpenAccount = false
    }
    let data = this.getMenuData()
    console.log('data', JSON.parse(JSON.stringify(data)))
    let tList = [] // 第二层标题
    let rList = {} // 第二次路径
    if (data && data.children && data.children.length > 0) {
      // 配置数据
      for (let index = 0; index < data.children.length; index++) {
        const element = data.children[index]
        let title = element.meta.title
        tList.push(title)
        let children = element.children || []
        let cList = [] // 存放第三层路径
        for (let i = 0; i < children.length; i++) {
          const e = children[i]
          if (!e.hidden) {
            let transformedChildren = []
            if (e.children && e.children.length > 0) {
              transformedChildren = e.children.map((child) => ({
                title: child.meta.title,
                path: child.path,
              }))
            }
            cList.push({
              title: e.meta.title,
              path: e.path,
              children: transformedChildren,
            })
          }
        }
        rList[title] = cList
      }
      this.titleList = tList
      // 重组菜单数据
      this.routeList = this.reorganizeMenuData(rList)
      // this.routeList = rList
      
      // 处理占位符
      if (this.routeList[this.titleList[0]][0].children.length <= 8) {
        this.routeList[this.titleList[0]][0].children.splice(5, 0, { title: '', isPlaceholder: true })
      }
    } else {
      // 本地数据
      this.titleList = subMenu.routeMap[this.path].titles
      this.routeList = subMenu.routeMap[this.path]
    }
  },
  methods: {
    // 添加新方法来重组菜单数据
    reorganizeMenuData(data) {
      let reorganizedData = {};
      
      // 初始化结果对象，保持原有的标题列表
      this.titleList.forEach(title => {
        reorganizedData[title] = [];
      });

      // 特殊处理"单据"分类
      if (data['单据']) {
        const billItems = data['单据'];
        const groupedBills = {};

        // 初始化分组
        Object.keys(this.menuGroups).forEach(group => {
          groupedBills[group] = {
            title: group,
            path: '/layouts/RouteView',
            children: []
          };
        });

        // 将每个单据项分配到对应的组
        billItems.forEach(item => {
          for (const [groupName, groupItems] of Object.entries(this.menuGroups)) {
            if (groupItems.includes(item.title)) {
              groupedBills[groupName].children.push(item);
              break;
            }
          }
        });

        // 只添加有子项的分组到最终结果
        reorganizedData['单据'] = Object.values(groupedBills).filter(group => group.children.length > 0);
      }

      // 处理其他分类
      Object.entries(data).forEach(([key, value]) => {
        if (key !== '单据') {
          reorganizedData[key] = value;
        }
      });

      return reorganizedData;
    },
    
    getMenuData() {
      let arr = this.$store.state.user.permissionList
      for (let index = 0; index < arr.length; index++) {
        const element = arr[index]
        if (element.path == this.path) {
          return element
        }
      }
    },
    routeClick(item) {
      console.log('item', item)
      if (item.isPlaceholder) {
        return
      }
      this.printPermissions = handleOtherPerms('打印模板设置')
      if (item.path == this.$route.path) {
        this.$emit('pathChange', 0)
        return
      }
      // 账套过期不允许进入其他页面
      if (Vue.ls.get('account-no-money')) {
        return this.$elMessage.warning('续费未完成不能操作!')
      }
      if (!this.isOpenAccount) {
        // 基本信息的资料都可以操作
        if (
          [
            '/initialAccountSetup',
            '/baseInfomation/material/commodityInfo',
            '/baseInfomation/material/transactionCompanyInfo',
            '/baseInfomation/material/staffInfo',
            '/baseInfomation/material/warehouseInfo',
            '/baseInfomation/material/logisticsInfo',
            '/baseInfomation/material/accountInfo',
          ].includes(item.path)
        ) {
          // 未选择开账不能进入基本信息页面
          if (this.openAccount === 0) {
            return this.$elMessage.warning('请先选择开账方式!')
          }
          return this.toPath(item)
        } else if (
          [
            '/baseInfomation/beginningOfPeriod/inventoryEntry',
            '/baseInfomation/beginningOfPeriod/arAndapEntry',
            '/baseInfomation/beginningOfPeriod/accountBalanceEntry',
          ].includes(item.path)
        ) {
          // 期初菜单需要处理
          if (this.openAccount === 0) {
            return this.$elMessage.warning('请先选择开账方式!')
          }
        } else {
          return this.$elMessage.warning('未开账不能操作!')
        }
      }
      if (
        [
          '/baseInfomation/printSetting/printSet',
          '/baseInfomation/printSetting/printSetRecord',
          '/baseInfomation/printSetting/printSetStatic',
          '/baseInfomation/printSetting/printSetStock',
          '/baseInfomation/printSetting/printSetSettlement',
          '/baseInfomation/printSetting/templateSet',
          '/baseInfomation/printSetting/library',
        ].includes(item.path) &&
        !this.printPermissions
      ) {
        return this.$elMessage.warning('未拥有打印模板设置权限！!')
      }
      // 现金银行统计表拦截是否有录入权限
      if (item.path == '/reportStatistics/financeReport/cashBankStatistics' && !this.cashPermissions.LuRu) {
        return this.$elMessage.warning('没有权限！')
      }
      const titleMappings = {
        '物流代收': '物流代收结算单',
        '物流代付': '物流代付结算单',
        '物流运费': '物流运费结算单',
        // 在此处添加其他需要转换的标题映射
      };
      const permissionTitle = titleMappings[item.title] || item.title;
      // 没有当前页面权限
      if (!handlePagePermissions(permissionTitle)) {
        return this.$elMessage.warning('没有权限！')
      }
      this.toPath(item)
    },
    toPath(item) {
      let path = item.path
      if (path == '/otherWarehouseType') {
        this.$emit('pathChange', 1)
      } else if (path == '/initialAccountSetup') {
        this.$emit('pathChange', 3)
      } else if (path == '/otherDeliveryType') {
        this.$emit('pathChange', 2)
      } else {
        this.$emit('pathChange', 0)
        this.$router.push(
          {
            path: item.path,
          },
          () => {},
          () => {}
        )
      }
    },
  },
}
</script>

<style lang="less" scoped>
.navigation {
  height: 100%;
  padding-bottom: 0.168761rem;

  .navigation-content {
    height: 100%;
    display: flex;
    gap: 16px;
    overflow: auto;
    .flex-center {
      flex: 4;
      background-color: #dbdbdb;
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 24px;

      .left-menu {
        width: 100%;
        display: flex;
        justify-content: center;
        gap: 40px;
        flex-shrink: 1;
        min-width: 600px; // 左侧区域最小宽度，防止过小导致换行或重叠
      }
      .menu-group {
        display: grid;
        gap: 40px 60px;
        padding: 50px;
        background-color: #fff;
        border-radius: 10px;
      }
      .menu-group:nth-child(1) {
        grid-template-columns: repeat(3, 1fr);
        grid-template-rows: repeat(3, 1fr);
      }
      .menu-group:nth-child(3) {
        grid-template-columns: repeat(2, 1fr);
        grid-template-rows: repeat(3, 1fr);
      }
      .menu-group-item1 {
        width: 100%;
        height: 100px;
        cursor: pointer;
        font-size: 17px;
        color: #000000;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        white-space: nowrap; // 防止文字换行

        img {
          width: 60px;
          margin-bottom: 15px;
        }
      }
      .placeholder {
        cursor: default !important;
        opacity: 0;
      }
    }

    /* 右侧统计列表区域 */
    .query_statistics {
      flex: 1;
      background: white;
      border-radius: 10px 10px 0px 0px;
      min-width: 250px; // 右侧区域的最小宽度

      .query_statistics_title {
        height: 56px;
        background: #fc6868 !important;
        border-radius: 10px 10px 0 0;
        font-size: 16px;
        font-weight: 600;
        color: white;
        display: flex;
        justify-content: center;
        align-items: center;
        white-space: nowrap; // 防止标题换行
      }

      .query_statistics_content {
        height: 85%;
        overflow: auto;
        margin-top: 25px;
        padding: 0 20px 0 30px;

        .query_statistics_content_item {
          cursor: pointer;
          height: 33px;
          font-size: 15px;
          color: #666;
          margin-bottom: 0;
          transition: all 0.2s;
          display: flex;
          align-items: center;
          white-space: nowrap; // 防止文字换行
          overflow: hidden;
          text-overflow: ellipsis;

          &:hover {
            color: #fc6868;
            transform: translateX(4px);
          }

          .yuan {
            width: 10px;
            height: 10px;
            background: linear-gradient(180deg, #fc6c6c 0%, #fd3131 100%);
            border-radius: 50%;
            margin-right: 10px;
          }
        }

        .ant-divider {
          margin: 15px 0;
          background: #E8E8E8;
        }
      }
    }
  }
  
}
</style>
